
package com.epam.android.training.level1.activity;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.db.dao.PollDao;
import com.epam.android.training.level1.db.dao.impl.PollDaoImpl;
import com.epam.android.training.level1.poll.PollBo;
import com.epam.android.training.level1.widget.CollectionAdapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

/**
 * Activity responsible for loading tests results from database and initiating
 * new test for user.
 * 
 * @author Anton Novikau
 */
public class PollsActivity extends BasePageActivity {

  private ListView pollsContainer;

  private LayoutInflater inflater;

  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.polls);
    pollsContainer = (ListView) findViewById(R.id.polls_container);
    inflater = getLayoutInflater();
    populatePollList();
    addItemClickAction();
  }

  private void populatePollList() {
    PollDao pollDao = new PollDaoImpl(this);
    List<PollBo> polls = pollDao.findAllPolls();
    pollsContainer.setAdapter(new PollAdapter(polls));
  }

  private void addItemClickAction() {
    pollsContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PollBo poll = (PollBo) parent.getItemAtPosition(position);
        int passedPercent = poll.getPassedPercent();
        if (passedPercent < 0) {
          openPoll(id);
        } else {
          createDialog(id, passedPercent).show();
        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case R.id.open_poll:
        if (resultCode == RESULT_OK) {
          long pollId = data.getLongExtra(POLL_ID_EXTRA, -1);
          int result = data.getIntExtra(POLL_RESULT_EXTRA, 0);

          PollAdapter adapter = (PollAdapter) pollsContainer.getAdapter();
          int childCount = adapter.getCount();
          for (int i = 0; i < childCount; i++) {

            PollBo poll = adapter.getItem(i);
            if (pollId == poll.getId()) {
              poll.setPassedPercent(result);
              adapter.notifyDataSetChanged();
            }
          }
        }
        break;
      default:
        super.onActivityResult(requestCode, resultCode, data);
        break;
    }
  }

  private Dialog createDialog(final long pollId, final int passedPercent) {
    AlertDialog.Builder warnDialog = new AlertDialog.Builder(this);
    warnDialog.setTitle(R.string.warning_title);
    warnDialog.setMessage(getString(R.string.poll_pass_again_message, passedPercent));
    warnDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int which) {
        openPoll(pollId);
      }
    });

    warnDialog.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {}
    });
    return warnDialog.create();
  }

  private void openPoll(long id) {
    Intent intent = new Intent(ACTION_SINGLE_POLL);
    intent.putExtra(POLL_ID_EXTRA, id);
    startActivityForResult(intent, R.id.open_poll);
  }

  private class PollAdapter extends CollectionAdapter<PollBo> {

    public PollAdapter(List<PollBo> items) {
      super(items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      PollViewHolder holder;
      if (convertView == null) {
        convertView = inflater.inflate(R.layout.poll_item, parent, false);
        holder = new PollViewHolder();
        holder.itemName = (TextView) convertView.findViewById(R.id.item_name);
        holder.itemStatus = (TextView) convertView.findViewById(R.id.item_status);

        convertView.setTag(holder);
      } else {
        holder = (PollViewHolder) convertView.getTag();
      }

      PollBo item = getItem(position);
      holder.itemName.setText(item.getDisplayName());
      int passed = item.getPassedPercent();
      if (passed > 0) {
        holder.itemStatus.setText(getString(R.string.status_passed, passed));
      } else {
        holder.itemStatus.setText(getString(R.string.status_new));
      }

      return convertView;
    }
  }

  private class PollViewHolder {
    private TextView itemName;

    private TextView itemStatus;
  }
}
